const fs = require("fs")
// const esprima = require("esprima")
// const estraverse = require("estraverse")
// const escodegen = require("escodegen")
const iconv = require("iconv-lite")

function getAllLetters() {
    // 生成大写字母字符串并转换为数组
    const upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    // 生成小写字母字符串并转换为数组
    const lowerCase = 'abcdefghijklmnopqrstuvwxyz'.split('');
    // 合并数组
    return [...upperCase, ...lowerCase];
}

function getAllLetterNums(){
    var letters = getAllLetters();
    const  nums = "0123456789".split('');
    return [...letters, ...nums];
}

/*
打乱数组顺序
 */
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]]; // 使用ES6的数组解构来交换元素
    }
    return array;
}

/*
生成一个长度为2/3的不重复的变量名列表
并打乱顺序
 */
function get_rand_names(old_names){
    var result = [];
    var letters = getAllLetters();
    var letterNums = getAllLetterNums();
    for(var i=0;i<letters.length;i++){
        for(var j=0;j<letterNums.length;j++){
            if(result.length>old_names.size*1.5){
                break
            }
            var n = letters[i]+letterNums[j];
            if(!old_names.has(n)){
                result.push(n);
            }

            for(var z=0;z<letterNums.length;z++){
                if(result.length>old_names.length*1.5){
                    break
                }
                n = letters[i]+letterNums[j]+letterNums[z]
                if(!old_names.has(n)){
                    result.push(n);
                }
            }
        }
    }
    shuffleArray(result);
    return result;
}

function get_file(file){
    var content = fs.readFileSync(file,{encoding:"binary"});
    var buf = new Buffer.from(content, "binary");
    var code = iconv.decode(buf, "utf-8");
    return code;
}

module.exports = {
    get_file,
    get_rand_names
}